package com.example.a10908.retorfitrxjava.utils;

import android.util.Log;

import com.example.a10908.retorfitrxjava.callback.ListviewDataCallBack;
import com.example.a10908.retorfitrxjava.model.bean.ListBean;
import com.example.a10908.retorfitrxjava.retorfitinterface.ListViewData;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 10908 on 2016/12/16.
 */

public class HttpUtils {
   private ListviewDataCallBack callBack;
    //提供一个单例
    private static HttpUtils httpUtils;

    public static HttpUtils getHttpUtils() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    public void setCallBackListener(ListviewDataCallBack callBack) {
        this.callBack = callBack;
    }

    public void listViewNet(String url, String path) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(url).
                client(new OkHttpClient()).
                addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        ListViewData listViewData = retrofit.create(ListViewData.class);

        Flowable<ListBean> flowable = listViewData.getData(path);
        flowable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ListBean>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        //开启请求
                        s.request(Long.MAX_VALUE);
                    }

                    @Override
                    public void onNext(ListBean listBean) {
                        callBack.getDataSuccess(listBean);
                        if(listBean==null)
                        Log.e("llllllllll","listBeanNext");
                    }

                    @Override
                    public void onError(Throwable t) {
                        callBack.getDataError(t.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
